package com.acwing.lc.part1;

import java.io.*;

/**
 * @author rkc
 * @date 2022/9/8 14:53
 */
public class LC8字符串转换整数atoi {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        writer.write(String.valueOf(myAtoi(reader.readLine())));
        writer.flush();
    }

    public static int myAtoi(String s) {
        char[] ch = s.toCharArray();
        int k = 0;
        while (k < s.length() && s.charAt(k) == ' ') k++;
        if (k == ch.length) return 0;
        int minus = 1;
        if (ch[k] == '-') {
            minus = -1;
            k++;
        } else if (ch[k] == '+') {
            k++;
        }
        int ans = 0;
        for (int i = k; i < ch.length && ch[i] >= '0' && ch[i] <= '9'; i++) {
            if (ch[i] >= '0' && ch[i] <= '9') {
                int x = ch[i] - '0';
                if (minus == 1 && ans > (Integer.MAX_VALUE - x) / 10) return Integer.MAX_VALUE;
                if (minus == -1 && -ans < (Integer.MIN_VALUE + x) / 10) return Integer.MIN_VALUE;
                if (-ans * 10 - x == Integer.MIN_VALUE) return Integer.MIN_VALUE;
                ans = ans * 10 + x;
            }
        }
        ans *= minus;
        return ans;
    }
}
